package org.example.sercurity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.Data;
import org.springframework.jca.cci.object.SimpleRecordOperation;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;
import java.util.stream.Collectors;

@Data
public class UserDeatilImpl implements UserDetails {
    private String username;
    private String password;
    private String nickName;
    private Set<String> roleNames  = new HashSet<>();
    private Set<String> permsList = new HashSet<>() ;

    /**
     * 在spring security调用注解鉴权时，自动调用
     * 将用户的角色和权限加入到Collection<? extends GrantedAuthority>集合
     * @return
     */
    @Override
    @JsonDeserialize(using = CustomAuthorityDeserializer.class)
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> list = new ArrayList<>();
//        for (String roleName : roleNames) {
//            SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_"+roleName);
//            list.add(authority);
//        }
//        for (String perms : permsList) {
//            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(perms);
//            list.add(authority);
//        }

            list.addAll(roleNames.stream().map(roleName -> new SimpleGrantedAuthority("ROLE_"+roleName)).collect(Collectors.toList()));
            list.addAll(permsList.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
        return list;
    }


    @Override
    public String getPassword() {
        return password;
    }


    @Override
    public String getUsername() {
        return username;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return true;
    }
}
